const path = require('path')
const fileUtils = require('../utils/file_utils.js')
// 引入webscoket
const WebSocket = require('ws')
// 创建webscoket服务端对象
const wss = new WebSocket.Server({
  port: 9998
})

module.exports.listen = () => {
  // 监听客户端的连接; client:代表客户端的连接socket对象
  wss.on('connection', client => {
    console.log('客户端连接成功')
    // 监听客户端的message事件; msg: 客户端发给服务端的数据
    client.on('message', async msg => {
      // console.log('客户端发送的信息是' + msg)
      let payload = JSON.parse(msg)
      const action = payload.action
      if(action === 'getData') {
        let filePath = '../data/' + payload.chartName + '.json'
        filePath = path.join(__dirname, filePath)
        const result = await fileUtils.getFileJsonData(filePath)
        // 服务端从客户端获取到的数据基础上增加字段data，data的值就是某json文件的内容
        payload.data = result
        client.send(JSON.stringify(payload))
      } else {
        // wss.clients: 所有客户端的连接
        wss.clients.forEach(client => {
          client.send(msg)
        })
      }

      // 服务端发送数据给客户端
      //client.send('hello from backend')
    })
  })
}
